/*
Copyright (c) 2010, Jonathan Baldwin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ScreenCapture.h"

namespace recap
{
ScreenCapture::ScreenCapture(QObject *parent) : QObject(parent), m_isRunning(false), m_videoCaptureThread(new SimpleThread(this, "doCaptureVideo")), m_encoderThread(new SimpleThread(this, "doEncode"))
{
}

ScreenCapture::~ScreenCapture()
{
    if (m_isRunning)
        stop();
}

bool ScreenCapture::isRunning() const
{
    return m_isRunning;
}

void ScreenCapture::setVideoOutputDevice(QIODevice& vod)
{
//  m_videoOut.outputDevice = &vod;
}

void ScreenCapture::stop()
{
    preStop();
    m_status = SC_Stat_Shutdown;
    if (!m_encoderThread->wait())
        m_encoderThread->terminate();
    if (!m_videoCaptureThread->wait())
        m_videoCaptureThread->terminate();
    m_isRunning = false;
    postStop();
    stopped();
}

void ScreenCapture::start()
{
    preStart();
    m_status = SC_Stat_Normal;
    m_videoCaptureThread->start();
    m_encoderThread->start();
    m_isRunning = true;
    postStart();
    started();
}

void ScreenCapture::preStart()
{
    m_x11Capture.open();
  
    m_encoder.m_in_pixfmt = PIX_FMT_RGB32;
    m_encoder.m_video_codecid = CODEC_ID_FFVHUFF;
    m_encoder.m_width = m_x11Capture.getWidth();
    m_encoder.m_height = m_x11Capture.getHeight();
    m_encoder.m_framerate = RECAP_FPS;
    m_encoder.m_in_picture_setbyuser = true;
    m_encoder.m_in_picture = avcodec_alloc_frame();
    //m_encoder.m_in_picture->data[0] = (uint8_t*) m_x11Data.image->data;
    //m_encoder.m_in_picture->linesize[0] = m_x11Data.image->bytes_per_line;
    //m_encoder.m_in_picture->data[0] = (uint8_t*) m_x11Capture.getFrame();
	      //m_encoder.m_in_picture->linesize[0] = m_x11Capture.getBytesPerLine();
	      
    m_encoder.m_enable_audio = false;
#if 0
    m_encoder.m_audio_codecid = CODEC_ID_;
    m_encoder.m_audio_channels = pasamplespec.channels;
    m_encoder.m_audio_samplerate = pasamplespec.rate;
    m_encoder.m_audio_sampleformat = SAMPLE_FMT_S16;
    m_encoder.m_samples_setbyuser = false;
#endif
    
    m_encoder.open("scrndump.mkv");
    
    m_startTime = Time();
}

void ScreenCapture::postStart()
{

}

void ScreenCapture::preStop()
{

}

void ScreenCapture::postStop()
{
  
  
    av_free(m_encoder.m_in_picture);
    m_encoder.close();

    m_x11Capture.close();
  //pa_simple_free(m_audioData.pa_handle);
}

void ScreenCapture::doCaptureVideo()
{
    //initialization goes here


    timeval time;
    unsigned long muframe = (1000000/60);
    int frameCount = 0;
    forever
    {
        switch ((int)m_status)
        {
        case SC_Stat_Pause:
            SimpleThread::msleep(200);
            continue;
        case SC_Stat_Shutdown:
            //cleanup here
        {
        }
        return;
        case SC_Stat_Normal:
        {
	  m_x11Capture.handleEvents();
        }
        }
    }
}

void ScreenCapture::doEncode()
{
    //timeval time;
    //unsigned long muframe = (1000000/30);
    Time frameTime(0, 1000000/RECAP_FPS);
    int frameCount = 0;
    
    forever
    {
        switch ((int)m_status)
        {
        case SC_Stat_Pause:
            SimpleThread::usleep(frameTime.microseconds);
            continue;
        case SC_Stat_Shutdown:
            //cleanup here
        {
            rDebug("%i frames encoded in %f seconds (%f fps, %f%%)", frameCount, (double)(Time()-m_startTime), frameCount/(double)(Time()-m_startTime), 100.0*(frameCount/(double)(Time()-m_startTime))/RECAP_FPS);
        }
        return;
        case SC_Stat_Normal:
        {
            //dump video here
            Time currentTime;
            if((currentTime = (Time()-m_startTime))/frameTime >= frameCount)
	    {  
	      m_encoder.m_in_picture->data[0] = (uint8_t*) m_x11Capture.getFrame();
	      m_encoder.m_in_picture->linesize[0] = m_x11Capture.getBytesPerLine();
	      m_encoder.writeVideoFrame();
	      frameCount++;
	    }
	    else
	      SimpleThread::usleep(1000);
	}
        }
    }
}
}

